package com.taobao.livis.others;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestThreadPoolForWhileTrueThread {
	public static void main(String[] args) {
		ExecutorService pool = Executors.newFixedThreadPool(5);
		List<Runnable> rs = new ArrayList<Runnable>();
		NotifyThread t = new NotifyThread(rs);
		pool.execute(t);
		for(int i=1;i<=100;i++){
			PrintThread p = new PrintThread(i,rs);
			pool.execute(p);
			//System.out.println(i);
		}
	}
}

class NotifyThread implements Runnable{
	
	public NotifyThread(List<Runnable> notruns){
		this.notruns = notruns;
	}
	
	List<Runnable> notruns;

	@Override
	public void run(){
		System.out.println("notifyThread start");
		while(true){
			if(notruns.size()>0){
				for(Runnable r:notruns){
					r.notify();
				}
			}
		}
	}
}

class PrintThread implements Runnable{
	
	List<Runnable> notruns;
	
	public void setNotruns(List<Runnable> notruns) {
		this.notruns = notruns;
	}

	private int pos;
	
	public PrintThread(int pos,List<Runnable> notruns){
		this.pos = pos;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		//System.out.println(Thread.currentThread().getName()+" start");
		while(true){ 
			System.out.println(Thread.currentThread().getName()+" print "+ pos);
			try {
				Thread.sleep(1000);
				synchronized(this){
					System.out.println(Thread.currentThread().getName()+" wait "+ pos);
					notruns.add(Thread.currentThread());
					wait();
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
}